<template>
  <div ref="canvas"></div>
</template>

<script lang="ts" setup>
import * as THREE from "three";
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls";
import { ref, onMounted } from "vue";
// @ts-ignore
import testPng from '@/assets/test.png'

// 画布
const canvas = ref<any>('');
// 场景
const scene = new THREE.Scene();
// 立方体几何对象Geometry
const geometry = new THREE.BoxGeometry(100, 100, 100);
// 材质的纹理贴图
const texture = new THREE.TextureLoader().load(testPng);
// 高光材质
const phongMaterial = new THREE.MeshPhongMaterial({
  color: 0xffffff,
  shininess: 10, // 高光部分的亮度，默认30 - 控制高光反射效果
  specular: 0x111111, // 高光部分的颜色 - 控制高光反射效果
  map: texture, // 纹理贴图
});
// 网格模型mesh
const mesh = new THREE.Mesh(geometry, phongMaterial);
scene.add(mesh);

// 光源
const spotLight = new THREE.SpotLight(0xffffff, 1.0, 500, Math.PI / 5);
spotLight.position.set(0,100, 0);
spotLight.target = mesh;
scene.add(spotLight);

const ambientLight = new THREE.AmbientLight(0xffffff, 0.4);
scene.add(ambientLight);
// 相机
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.set(200, 200, 200);
camera.lookAt(0, 0, 0);
// 渲染器
const renderer = new THREE.WebGLRenderer({
  antialias: true, // 开启抗锯齿 - 减少在计算机屏幕上呈现的图像中出现的锯齿状边缘。锯齿状边缘是由于图像分辨率不足而导致的，这种情况在显示锐利直线或曲线时尤为明显
});
// 不同硬件设备的屏幕的设备像素比window.devicePixelRatio值可能不同
console.log('查看当前屏幕设备像素比: ', window.devicePixelRatio);
// 获取你屏幕对应的设备像素比告诉 threeJs, 以免渲染模糊问题
renderer.setPixelRatio(window.devicePixelRatio);
// 设置背景颜色
renderer.setClearColor(0x444444, 1);

renderer.setSize(window.innerWidth, window.innerHeight);
// 渲染函数
function render() {
  mesh.rotation.x += 0.01;
  mesh.rotation.y += 0.02;
  renderer.render(scene, camera);
  requestAnimationFrame(render);
}

// 设置相机控件轨道控制器OrbitControls
const controls = new OrbitControls(camera, renderer.domElement);
// 相机控件.target属性在OrbitControls.js内部表示相机目标观察点，默认0,0,0
controls.update();

// 挂载之后进行实际的渲染
onMounted(() => {
  canvas.value.appendChild(renderer.domElement);
  render();
});

</script>
